
package edu.ntnu.superrss.controller;

import edu.ntnu.superrss.controller.domain.FormComment;
import edu.ntnu.superrss.models.Comment;
import edu.ntnu.superrss.models.SyndEntryImpl;
import edu.ntnu.superrss.models.User;
import edu.ntnu.superrss.service.UserService;
import edu.ntnu.superrss.utils.HibernateUtil;
import javax.servlet.http.HttpSession;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

/**
 *
 * @author Dyre Hult <dyre.hult at gmail.com>
 */
@Controller
@SessionAttributes("user")
public class CommentController {
    private UserService us;
    @Autowired
    public void setUs(UserService us) {
        this.us = us;
    }

	
	@RequestMapping(value="/addComment.htm", method=RequestMethod.POST)
	public String processSubmit(@ModelAttribute("formComment") FormComment formComment, @ModelAttribute("user") User user,
                                    ModelMap model, HttpSession session) {
                Session sess = HibernateUtil.getSessionFactory().openSession();
                sess.beginTransaction();

                SyndEntryImpl entry = (SyndEntryImpl)sess.createQuery("from SyndEntryImpl where id=?").setParameter(0, formComment.getFeedEntryId()).uniqueResult();
                user = (User)sess.get(User.class, user.getUsername());
//                SyndEntryImpl entry = (SyndEntryImpl)sess.get(SyndEntryImpl.class, formComment.getFeedEntryId());

                Hibernate.initialize(entry.getComments());
                Comment comment = new Comment(formComment.getContent());
                comment.setUser(user);
//                comment.setEntrysource(entry);
                entry.addComment(comment);
                sess.merge(entry);
//                sess.saveOrUpdate(comment);

                
                sess.flush();
                sess.getTransaction().commit();
                sess.close();
                
                return "redirect:index.htm";
	}
}